package cn.com.KnowNews.servlet;

import cn.com.KnowNews.entity.News;
import cn.com.KnowNews.service.ICategoryService;
import cn.com.KnowNews.service.INewsService;
import cn.com.KnowNews.service.imlp.CategoryServiceImpl;
import cn.com.KnowNews.service.imlp.NewsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "ShowAllNewsServlet",urlPatterns = "/ShowAllNews")
public class ShowAllNewsServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();
        List<News> allNews = (ArrayList<News>) session.getAttribute("news");
        if(allNews==null){
            try {
                INewsService newsService = new NewsServiceImpl();
                allNews = newsService.showAllNews();
            } catch (Exception e) {
                e.printStackTrace();
            }
            request.getSession().setAttribute("news",allNews);
        }

        int countPerPage = 6;
        String pageIndex = request.getParameter("pageIndex");
        if(pageIndex==null){
            pageIndex = "1";
        }
        int currentPageIndex = Integer.parseInt(pageIndex);

        int pageCount;

        if(allNews.size()/countPerPage==0){
            pageCount = allNews.size()/countPerPage;
        }else{
            pageCount = allNews.size()/countPerPage+1;
        }
        ArrayList<News> pageNews = new ArrayList<>();
        int begin = (currentPageIndex-1)*countPerPage;
        int end = currentPageIndex*countPerPage-1;
        if(end>=allNews.size()-1) {
            end=allNews.size()-1;
        }
        for(int i=begin;i<=end;i++){
            pageNews.add(allNews.get(i));
        }
        session.setAttribute("pageNews",pageNews);

        session.setAttribute("pageCount",pageCount);
        session.setAttribute("newsCount",allNews.size());
        session.setAttribute("currentPageIndex",currentPageIndex);
        session.setAttribute("countPerPage",countPerPage);

        response.sendRedirect("/admin/index.jsp");
    }
}
